import {Component, OnInit} from '@angular/core';
import {DeviceService} from '../../../svc/device.svc';
import {MenuItem} from 'primeng/api';
import {Router} from '@angular/router';
import {TranslateService} from '@ngx-translate/core';

@Component({
    selector: 'app-firmware-upgrade',
    templateUrl: './firmware-upgrade.component.html',
    styleUrls: ['./firmware-upgrade.component.css']
})
export class FirmwareUpgradeComponent implements OnInit {
    firmwareUpgradeInformation = {
        WEBFirmwareVersion: '',
        BCGFirmwareVersion: ''
    };
    selectedFirmwareUpgrade = false;
    hintFirmwareUpgrade = false;
    hintFactoryReset = false;
    file: any;
    clearFiles: any;
    stepItems: MenuItem[];
    stepActiveIndex = 0;
    fuShowUIIndex = 0;
    fuUpgradeProgress = 0;
    fuResult = true;
    fuReboot = false;
    fuResultMsg: string;

    constructor(private dsv: DeviceService, private router: Router, private translate: TranslateService) {
        dsv.fuComponent.subscribe(() => {
            this.stepItems = [{label: this.translate.instant('select_update')}
                , {label: this.translate.instant('updating')}
                , {label: this.translate.instant('complete_all')}];
        });
    }

    ngOnInit(): void {
        this.dsv.onChangeLanguage();
        this.dsv.getSystemInformationData().subscribe(version => {
            const fuVersion = JSON.parse(JSON.stringify(version));
            this.firmwareUpgradeInformation.BCGFirmwareVersion = fuVersion.BCGVersion;
            this.firmwareUpgradeInformation.WEBFirmwareVersion = fuVersion.webVersion;
        });
    }

    sendUpgradeFile(reboot): void {
        this.fuShowUIIndex = 1;
        this.stepActiveIndex = 1;
        this.hintFirmwareUpgrade = false;
        const httpRequest = new XMLHttpRequest();
        httpRequest.open('post', this.dsv.url + '/upload');

        httpRequest.upload.onprogress = event => {
            if (event.lengthComputable) {
                this.fuUpgradeProgress = Math.round(event.loaded / event.total * 100);
            }
        };

        httpRequest.onreadystatechange = () => {
            if (httpRequest.readyState === 4 && httpRequest.status === 200) {
                const resData = JSON.parse(httpRequest.responseText);
                if (resData.OTAStatus === 'succeed') {
                    this.fuResult = true;
                    this.fuResultMsg = this.translate.instant('message3');
                    this.fuShowUIIndex = 2;
                    this.stepActiveIndex = 2;
                    if (reboot) {
                        setTimeout(() => {
                            this.dsv.sendRebootRequest().subscribe(msg => {
                                const result = JSON.parse(JSON.stringify(msg));
                                if (result.status === 0) {
                                    this.fuReboot = true;
                                }
                            });
                        }, 500);
                    }
                }
                else {
                    this.fuResult = false;
                    switch (resData.errorCode) {
                        case 1:
                            this.fuResultMsg = this.translate.instant('error_message1');
                            break;
                        case 2:
                            this.fuResultMsg = this.translate.instant('error_message2');
                            break;
                        case 3:
                            this.fuResultMsg = this.translate.instant('error_message3');
                            break;
                        case 4:
                            this.fuResultMsg = this.translate.instant('error_message4');
                            break;
                        case 5:
                            this.fuResultMsg = this.translate.instant('error_message5');
                            break;
                        case 6:
                            this.fuResultMsg = this.translate.instant('error_message6');
                            break;
                        case 7:
                            this.fuResultMsg = this.translate.instant('error_message7');
                            break;
                        case 8:
                            this.fuResultMsg = this.translate.instant('error_message8');
                            break;
                        case 9:
                            this.fuResultMsg = this.translate.instant('error_message9');
                            break;
                        case 10:
                            this.fuResultMsg = this.translate.instant('error_message10');
                            break;
                        case 11:
                            this.fuResultMsg = this.translate.instant('error_message11');
                            break;
                    }
                    this.fuShowUIIndex = 2;
                    this.stepActiveIndex = 2;
                }
            }
            else if (httpRequest.readyState === 4) {
                this.fuResult = false;
                this.fuResultMsg = this.translate.instant('message4');
                this.fuShowUIIndex = 2;
                this.stepActiveIndex = 2;
            }
        };
        httpRequest.send(this.file);
    }

    sendFactoryReset(): void {
        this.dsv.sendFactoryResetRequest().subscribe(msg => {
            const result = JSON.parse(JSON.stringify(msg));
            if (result.status === 0) {
                location.reload(true);
            }
        });
    }

    onSelect_FileUpload(event, fu): void {
        let isValid = true;
        if (event.files.length > 1) {
            isValid = false;
        }
        else {
            if (event.files[0].name.substr(event.files[0].name.length - 3, 3).toUpperCase() !== 'BIN') {
                isValid = false;
            }
        }
        if (isValid) {
            this.file = event.files[0];
            this.clearFiles = fu;
            this.hintFirmwareUpgrade = true;
        }
        else {
            fu.clear();
        }
    }

    dialogClose(fu): void {
        this.stepActiveIndex = 0;
        this.fuShowUIIndex = 0;
        this.fuUpgradeProgress = 0;
        fu.clear();
    }

    onReboot(): void {
        if (this.fuReboot) {
            location.reload(true);
        }
        this.selectedFirmwareUpgrade = false;
    }
}
